<template>
    <page-wrapper>
        <table-search v-if="isSearch" @search="search(1)" @reset="reset()">
            <template slot="form">
                <form-item label="">
                    <a-input v-model.trim="form.name" placeholder="员工姓名" />
                </form-item>
                <!-- <form-item label="">
                    <a-input v-model.trim="form.manager" placeholder="主管姓名" />
                </form-item> -->
                <form-item label="">
                    <a-tree-select
                        v-model="form.deptId"
                        allowClear
                        style="width:240px"
                        :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                        :tree-data="deptList"
                        :replaceFields="{ children: 'children', title: 'deptName', key: 'deptId', value: 'deptId' }"
                        placeholder="请选择部门"
                    >
                    </a-tree-select>
                </form-item>
                <form-item label="">
                    <a-select v-model="form.status" style="width: 120px" allowClear placeholder="请选择状态">
                        <a-select-option value="A">在职</a-select-option>
                        <a-select-option value="I">离职</a-select-option>
                    </a-select>
                </form-item>
            </template>
            <template slot="extra">
                <a-button
                    class="filter-item"
                    type="primary"
                    icon="plus"
                    @click="addInfo()"
                    :disabled="hasPerm(['staff:group:add'])"
                    >新增员工</a-button
                >
                <a-button
                    class="filter-item btn_space"
                    type="danger"
                    @click="remove()"
                    :disabled="hasPerm(['staff:group:remove']) || !selectionBox.length"
                    icon="delete"
                    >删除</a-button
                >
            </template>
        </table-search>
        <div class="table_scroll">
            <table-list
                :loading="loading"
                :columns="columns"
                :data="list"
                rowKey="id"
                :pagination="pagination"
                :scroll="isConcise?{x:true}:{ x: 1400 }"
                :selection="isSelection ? selection : null"
            >
                <template slot="imageUrl" slot-scope="{ text }">
                    <a-avatar @click="showPreview(text)" shape="square" :size="64" :src="text" />
                </template>
                <template slot="deptId" slot-scope="{ text }">
                    <field-tag :value="text" type="deptId" showType="deptName" :data="expandDeptData"></field-tag>
                </template>
                <template slot="roleId" slot-scope="{ text }">
                    <field-tag :value="text.roleId" type="roleId" showType="roleName" :data="roleList"></field-tag>
                </template>
                <template slot="sex" slot-scope="{ text }">
                    {{ text == 'M' ? '男' : '女' }}
                </template>
                <template slot="insureStatus" slot-scope="{ text }">
                    {{ text == 1 ? '是' : '否' }}
                </template>
                <template slot="switch" slot-scope="{ text }">
                    <a-switch
                        checked-children="在职"
                        un-checked-children="离职"
                        :disabled="hasPerm(['staff:group:update'])"
                        :key="text.tenantId"
                        :default-checked="text.status == 'A' ? true : false"
                        @change="onSwitchStatus(text)"
                    />
                        <!-- :disabled="hasPerm(['sys:user:update'])" -->
                </template>
                <template slot="action" slot-scope="{ text, index }">
                    <a-button
                        size="small"
                        type="primary"
                        :disabled="hasPerm(['staff:group:update'])"
                        @click="addInfo(text, index)"
                        >编辑</a-button
                    >
                    <a-button
                        type="danger"
                        size="small"
                        class="btn_space"
                        :disabled="hasPerm(['staff:group:remove'])"
                        @click="remove(text)"
                    >
                        删除
                    </a-button>
                </template>
            </table-list>
        </div>

        <template v-if="isShowInfo">
            <user-info :info="itemInfo" :deptList="deptList" :roleList="roleList" @cancel="isShowInfo = false" @submit="submit" />
        </template>

        <a-modal v-model="isPreview" :footer="null" style="width:400px;" title="查看人脸">
            <img style="width:100%" :src="previewUrl" />
        </a-modal>
    </page-wrapper>
</template>
<script>
import table from '@/mixins/table';
import { columns,conciseColumns } from './columns';
import UserInfo from './components/info.vue';
import { mapState } from 'vuex';
import {getCache} from '@/utils/session'
import deptApi from '@/api/system/dept';
import roleApi from '@/api/system/role'
import { remoteList, deleteInfo, updateInfo } from '@/api/system/staff';

export default {
    name: 'UserList',
    mixins: [table],
    props: {
        params: {
            //列表接口筛选的参数
            type: Object,
            default: () => {}
        },
        isSelection:{//是否可以多选
            type: Boolean,
            default: true
        },
        isSearch: {
            type: Boolean,
            default: true
        },
        isConcise:{//是否简约版 即简单的显示基本信息
            type:Boolean,
            default:false
        }
    },
    components: {
        UserInfo
    },
    computed: {
        ...mapState({
            account: state => state.user.accountInfo
        })
    },
    data() {
        let originForm = {
            name: null,
            manager: '',
            status: undefined,
            deptId: undefined
        };
        return {
            originForm,
            columns:!this.isConcise?columns:conciseColumns,
            form: {
                ...originForm
            },
            itemInfo: null,
            isShowInfo: false,
            list: [],
            deptList: [],
            roleList:[],
            expandDeptData: [],
            isShowPwd: false,
            isPreview: false,
            previewUrl: ''
        };
    },
    watch: {
        params: {
            handler(now, pre) {
                if (JSON.stringify(now) == JSON.stringify(pre)) return false;
                this.form = { ...this.form, ...now };
                this.search(1);
            },
            deep: true
        }
    },
    async created() {
        await this.getResource();
        await this.getRoleList();
        this.search(1);
    },
    methods: {
        async search(page) {
            try {
                this.loading = true;
                if (page) {
                    this.form.page = page;
                }
                this.list = [];
                let res = await remoteList(this.form);
                let { list, total } = res.data;
                this.list = list;
                this.total = total;
            } finally {
                this.loading = false;
            }
        },
        //显示添加用户
        addInfo(item = {}) {
            this.isShowInfo = true;
            this.itemInfo = item;
        },
        //是否开启
        async onSwitchStatus(item) {
            console.log(item);
            try {
                let { status } = item;
                item.status = status == 'A' ? 'I' : 'A';
                this.loading = true;
                await updateInfo(item);
                this.$message.success('操作成功!');
            } catch (err) {
                let { status } = item;
                item.status = status == 'A' ? 'I' : 'A';
            } finally {
                this.loading = false;
            }
        },
        //更新数据
        submit() {
            this.isShowInfo = false;
            this.isShowPwd = false;
            this.search(1);
        },
        showPreview(text) {
            this.isPreview = true;
            this.previewUrl = text;
        },
        //删除
        remove(item = '') {
            this.$confirm({
                title: '提示',
                content: '确定要删除员工信息？',
                okText: '确定',
                cancelText: '取消',
                onOk: async () => {
                    try {
                        let ids = [];
                        if (item) {
                            ids = [item.id];
                        } else {
                            let selectionBox = this.selectionBox;
                            console.log(selectionBox);
                            selectionBox.map(async item => {
                                ids.push(item.id);
                            });
                        }
                        await deleteInfo({ ids });
                        this.$message.success('删除成功!');
                        this.search(1);
                    } catch (err) {}
                },
                onCancel() {}
            });
        },
        //获取资源列表信息
        async getResource() {
            let userInfo = getCache('userInfo') || { userId: '' };
            let { userId } = userInfo;
            let deptResult = await deptApi.remoteList({userId});
            let departData = [
                    {
                        deptName:'浙江交工集团',
                        key:'zj_group',
                        deptId:'-1',
                        parentId:'-2',
                        children:[
                            ...deptResult.data
                        ]
                    }
                ]
            this.deptList = departData;
            this.expandDeptData = [];
            this.expandData(departData);
        },
        //多层次数据展开
        expandData(data) {
            if (Array.isArray(data)) {
                data.map(item => {
                    this.expandDeptData.push(item);
                    if (item.children && item.children.length) {
                        this.expandData(item.children);
                    }
                });
            }
        },
        //获取角色列表
        async getRoleList(){
            try{
                let res = await roleApi.remoteList({
                    page:1,
                    size:100
                });
                let {list} = res.data;
                this.roleList = list;
            }finally{}
        }
    }
};
</script>
